package com.ibbt.musicplayer.client.panels;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PushButton;
import com.gwittit.client.facebook.ConnectState;
import com.gwittit.client.facebook.FacebookApi;
import com.gwittit.client.facebook.FacebookConnect;
import com.gwittit.client.facebook.entities.UserInfo;
import com.ibbt.musicplayer.client.LayoutResources;

public class Facebook_UserPanel extends AbsolutePanel {

	private final String APIKEY = "dafffb185716bfdfd619484afb3919b4";
	private final FacebookApi apiClient = GWT.create(FacebookApi.class);
	private Image imageFacebookUser;
	private Image imageFacebookButton;
	private Label labelConnect;
	
	public Facebook_UserPanel() {
		setStyleName("userframe");

		// Initialize Facebook Connect
		FacebookConnect.init(APIKEY);

		// Wait until we can determine status, then render rest of the app.
		FacebookConnect.waitUntilStatusReady(new WhenReadyCallback());
	}

	/** UI rendered when connected */
	public void renderWhenConnected() {
		// Gegevens van de geconnecteerde gebruiker ophalen
		apiClient.usersGetLoggedInUser(new getLoggedInUserCallback());
	}

	/** Get user info from server */
	private void getUserInfo(Long uid) {
		List<Long> uids = new ArrayList<Long>();
		uids.add(new Long(uid));

		// Add fields that should be returned
		List<String> fields = new ArrayList<String>();
		fields.add("pic_square");
		fields.add("first_name");
		fields.add("last_name");
		apiClient.usersGetInfo(uids, fields, new getUserInfoCallback());
	}

	/** Display basic user info */
	private void showUserInfo(List<UserInfo> userInfo) {
		this.clear();
		
		UserInfo ui = userInfo.get(0);
		
		// user image toevoegen
		imageFacebookUser = new Image(ui.getPicSquare());
		imageFacebookUser.addStyleName("userimg");
		add(imageFacebookUser, 0, 0);

		// Tekst: voornaam en naam
		labelConnect = new Label(ui.getFirstName() + " " + ui.getLastName());
		labelConnect.addStyleName("connect");
		add(labelConnect, 62, 0);
		
		// login button toevoegen
		imageFacebookButton = new Image(LayoutResources.INSTANCE.facebooklogout());
		imageFacebookButton.addClickHandler(new LogoutClickHandler());
		add(imageFacebookButton, 15, 75);
	}

	/** UI rendered when not connected */
	public void renderWhenNotConnected() {

		this.clear();

		// Default user image toevoegen
		imageFacebookUser = new Image(LayoutResources.INSTANCE.defaultuser());
		imageFacebookUser.addStyleName("userimg");
		add(imageFacebookUser, 0, 0);

		// Tekst: niet verbonden
		labelConnect = new Label("Niet verbonden met facebook");
		labelConnect.addStyleName("connect");
		add(labelConnect, 62, 0);

		// login button toevoegen
		imageFacebookButton = new Image(
				LayoutResources.INSTANCE.facebooklogin());
		imageFacebookButton.addClickHandler(new LoginClickHandler());
		add(imageFacebookButton, 15, 75);
	}

	
	
	/*************************** EVENT HANDLERS ***********************/
		
	/** Executed login when user clicks login-link */
	private class LoginClickHandler implements ClickHandler {
		public void onClick(ClickEvent event) {
			FacebookConnect.requireSession(new AsyncCallback<Boolean>() {
				public void onFailure(Throwable caught) {
					Window.alert("Failed");
				}

				public void onSuccess(Boolean result) {
					renderWhenConnected();
				}
			});
		}
	}

	/** Executed when user logs out */
	private class LogoutClickHandler implements ClickHandler {
		public void onClick(ClickEvent event) {
			FacebookConnect.logoutAndRedirect("/MyMusicPlayer.html?gwt.codesvr=127.0.0.1:9997");
		}
	};
	
	/*************************** CALLBACK CLASSES ************************/
		
		
	/** Callback fired when connect state is ready */
	private class WhenReadyCallback implements AsyncCallback<ConnectState> {
		public void onFailure(Throwable caught) {
			Window.alert("Failed to get facebook connect status, hit reload");
		}

		public void onSuccess(ConnectState result) {
			if (result == ConnectState.connected) {
				renderWhenConnected();
			} else {
				renderWhenNotConnected();
			}
		}
	};
	
	/** Callback to execute when user is logged in */
	private class getLoggedInUserCallback implements AsyncCallback<Long> {
		public void onFailure(Throwable caught) {
			// error bij het ophalen van UserId
		}

		public void onSuccess(Long uid) {
			getUserInfo(uid);
		}
	};

	/** Callback to execute when getting user info from Facebook */
	private class getUserInfoCallback implements AsyncCallback<List<UserInfo>> {
		public void onFailure(Throwable caught) {
			// fout
		}

		public void onSuccess(List<UserInfo> result) {
			showUserInfo(result);
		}
	};

}